package handler

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	. "service/goods_srv/global"
	"service/goods_srv/model"
	"service/goods_srv/proto"
)

// 获取轮播图列表
func (g *GoodsServer) BannerList(context.Context, *emptypb.Empty) (*proto.BannerListResponse, error) {
	var banners []*model.Banner
	result := DB.Find(&banners)
	if result.Error != nil {
		return nil, result.Error
	}

	var resData []*proto.BannerResponse
	for _, banner := range banners {
		resData = append(resData, &proto.BannerResponse{
			Id:    banner.ID,
			Index: banner.Index,
			Image: banner.Image,
			Url:   banner.Url,
		})
	}
	return &proto.BannerListResponse{
		Total: int32(result.RowsAffected),
		Data:  resData,
	}, nil
}

// 创建轮播图
func (g *GoodsServer) CreateBanner(c context.Context, r *proto.BannerRequest) (*proto.BannerResponse, error) {
	banner := new(model.Banner)
	result := DB.Where(&model.Banner{Image: r.Image}).First(banner)
	if result.RowsAffected == 1 {
		return nil, status.Errorf(codes.AlreadyExists, "轮播图已存在")
	}

	banner = &model.Banner{
		Image: r.Image,
		Url:   r.Url,
		Index: r.Index,
	}
	result = DB.Create(banner)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &proto.BannerResponse{
		Id:    banner.ID,
		Image: banner.Image,
		Url:   banner.Url,
		Index: banner.Index,
	}, nil
}

// 删除轮播图
func (g *GoodsServer) DeleteBanner(c context.Context, r *proto.BannerRequest) (*emptypb.Empty, error) {
	banner := new(model.Banner)
	banner.ID = r.Id

	result := DB.Where(banner).First(banner)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "轮播图不存在")
	}

	result = DB.Delete(&banner)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &empty.Empty{}, nil
}

// 更新轮播图
func (g *GoodsServer) UpdateBanner(c context.Context, r *proto.BannerRequest) (*emptypb.Empty, error) {
	banner := new(model.Banner)
	banner.ID = r.Id

	result := DB.Where(banner).First(banner)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "轮播图不存在")
	}

	// 请求参数中包含零值字段也要更新
	result = DB.Model(banner).Updates(map[string]interface{}{
		"index": r.Index,
		"image": r.Image,
		"url":   r.Url,
	})
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &empty.Empty{}, nil
}
